package Medium;

import Structures.TreeNode;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class LC0199 {
    public List<Integer> rightSideView(TreeNode root) {
        ArrayList<Integer> ret = new ArrayList<>();
        if (root == null) return ret;

        Queue<TreeNode> queue = new LinkedList<>();
        int thisLevelCount = 0, nextLevelCount = 0;
        queue.add(root);
        thisLevelCount++;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            thisLevelCount--;
            if (node.left != null) {
                queue.add(node.left);
                nextLevelCount++;
            }
            if (node.right != null) {
                queue.add(node.right);
                nextLevelCount++;
            }


            if (thisLevelCount == 0) { // 开始遍历下一层
                ret.add(node.val);
                thisLevelCount = nextLevelCount;
                nextLevelCount = 0;
            }
        }

        return ret;
    }
}
